package cn.iocoder.yudao.module.cmt.service.content;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import cn.iocoder.yudao.module.cmt.controller.admin.content.vo.*;
import cn.iocoder.yudao.module.cmt.dal.dataobject.content.ContentLikeDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.cmt.dal.mysql.content.ContentLikeMapper;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.cmt.enums.ErrorCodeConstants.*;

@Service
@Validated
public class ContentLikeServiceImpl implements ContentLikeService {

    @Resource
    private ContentLikeMapper contentLikeMapper;

    @Override
    public Long createLike(ContentLikeSaveReqVO createReqVO) {
        ContentLikeDO like = BeanUtils.toBean(createReqVO, ContentLikeDO.class);
        contentLikeMapper.insert(like);
        return like.getId();
    }

    @Override
    public void updateLike(ContentLikeSaveReqVO updateReqVO) {
        validateLikeExists(updateReqVO.getId());
        ContentLikeDO updateObj = BeanUtils.toBean(updateReqVO, ContentLikeDO.class);
        contentLikeMapper.updateById(updateObj);
    }

    @Override
    public void deleteLike(Long id) {
        validateLikeExists(id);
        contentLikeMapper.deleteById(id);
    }

    private void validateLikeExists(Long id) {
        if (contentLikeMapper.selectById(id) == null) {
            throw exception(LIKE_NOT_EXISTS);
        }
    }

    @Override
    public ContentLikeDO getLike(Long id) {
        return contentLikeMapper.selectById(id);
    }

    @Override
    public PageResult<ContentLikeDO> getLikePage(ContentLikePageReqVO pageReqVO) {
        return contentLikeMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteLikeListByIds(List<Long> ids) {
        ids.forEach(this::validateLikeExists);
        contentLikeMapper.deleteBatchIds(ids);
    }

}
